package com.pg.controller.dd;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pg.entity.EipTemp;
import com.pg.entity.cj.Jjd;
import com.pg.entity.dd.EipOperation;
import com.pg.service.EipOperationService;
import com.pg.service.EipTempService;
import com.pg.utils.PoiReadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 报工信息前端控制器
 * </p>
 *
 * @author likl
 * @since 2020-07-06
 */
@Api(tags = "报工信息")
@RestController
@RequestMapping("/eipOperation")
@Slf4j
public class EipOperationController extends JeecgController<EipOperation, EipOperationService> {

    @Autowired
    private EipOperationService eipOperationService;

    @Autowired
    private EipTempService eipTempService;

    /**
     * 添加 报工信息
     *
     * @param eipOperation 报工信息
     * @return 是否成功
     */
    @ApiOperation("添加 报工信息")
    @AutoLog(value = "ManualImport")
    @RequestMapping(method = RequestMethod.POST, value = "/add")
    public Result<?> add(@Valid @RequestBody EipOperation eipOperation) {
        EipOperation eipOperationByInsideNo = eipOperationService.selectByInsideNo(eipOperation.getInsideNo());
        if (eipOperationByInsideNo != null) {
            return Result.error("产品内部ID号重复！");
        } else {
            eipOperation.setPuid(UUID.randomUUID().toString());
            eipOperationService.save(eipOperation);
            return Result.ok("添加成功！");
        }
    }

    /**
     * 编辑 报工信息
     *
     * @param eipOperation 报工信息
     * @return 是否成功
     */
    @ApiOperation("编辑 报工信息")
    @AutoLog(value = "ManualImport")
    @RequestMapping(method = RequestMethod.POST, value = "/edit")
    public Result<?> edit(@Valid @RequestBody EipOperation eipOperation) {
        eipOperationService.updateById(eipOperation);
        return Result.ok("修改成功！");
    }

    /**
     * 临时编辑 报工信息
     *
     * @param eipOperation 报工信息
     * @return 是否成功
     */
    @ApiOperation("临时编辑 报工信息")
    @AutoLog(value = "DataCheck")
    @RequestMapping(method = RequestMethod.POST, value = "/editTemp")
    public Result<?> editTemp(@Valid @RequestBody EipOperation eipOperation, HttpServletRequest req) {
        String userName = (String) req.getSession().getAttribute("userName");
        EipTemp eipTemp = new EipTemp();
        eipTemp.setDataType("报工信息");
        eipTemp.setModUser(userName);
        eipTemp.setModTime(new Date());
        eipTemp.setLinkPUID(eipOperation.getPuid());
        eipTemp.setDetailedInformation(JSONObject.toJSONString(eipOperation));
        try {
            eipOperationService.updateOperation(eipTemp);
            return Result.ok("修改成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("修改失败！");
        }
    }

    /**
     * 通过id删除 报工信息
     *
     * @param id 全库唯一码
     * @return 是否成功
     */
    @ApiOperation("通过id删除 报工信息")
    @AutoLog(value = "通过id删除 报工信息")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        eipOperationService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除 报工信息
     *
     * @param ids 全库唯一码集合
     * @return 是否成功
     */
    @ApiOperation("批量删除 报工信息")
    @AutoLog(value = "批量删除 报工信息")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.eipOperationService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id逻辑删除 报工信息
     *
     * @param id 全库唯一码
     * @return 是否成功
     */
    @ApiOperation("通过id逻辑删除 报工信息")
    @AutoLog(value = "通过id逻辑删除 报工信息")
    @DeleteMapping(value = "/logicalDelete")
    public Result<?> logicalDelete(@RequestParam(name = "id", required = true) String id) {
        eipOperationService.logicalDelete(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量逻辑删除 报工信息
     *
     * @param ids 全库唯一码集合
     * @return 是否成功
     */
    @ApiOperation("批量逻辑删除 报工信息")
    @AutoLog(value = "批量逻辑删除 报工信息")
    @DeleteMapping(value = "/logicalDeleteBatch")
    public Result<?> logicalDeleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        eipOperationService.logicalDeleteBatch(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询 报工信息
     *
     * @param puid 全库唯一码
     * @return 报工信息数据
     */
    @ApiOperation("通过id查询 报工信息")
    @AutoLog(value = "DataCheck")
    @RequestMapping(method = RequestMethod.GET, value = "/selectByPuid")
    public Result<?> selectByPuid(@RequestParam(name = "puid") String puid) {
        EipOperation byId;
        byId = eipTempService.selectOperationByLinkPUID(puid);
        if (byId == null) {
            byId = eipOperationService.selectByPuid(puid);
            if (byId == null) {
                return Result.error("未找到对应数据");
            }
        }
        return Result.ok(byId);
    }

    /**
     * 通过产品内部ID查询 报工信息
     *
     * @param insideNo 产品内部ID
     * @return 是否成功
     */
    @ApiOperation("通过产品内部ID查询 报工信息")
    @AutoLog(value = "DataCheck")
    @RequestMapping(method = RequestMethod.GET, value = "/selectByInsideNo")
    public Result<?> selectByInsideNo(@RequestParam(name = "insideNo") String insideNo) {
        EipOperation byInsideNo;
        byInsideNo = eipOperationService.selectByInsideNo(insideNo);
        if (byInsideNo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(byInsideNo);
    }

    /**
     * 分页列表查询 报工信息
     *
     * @param eipOperation        报工信息
     * @param planStartTimeBegin  起始时间
     * @param planStartTimeFinish 结束时间
     * @param pageNo              起始页
     * @param pageSize            每页页数
     * @param req                 参数
     * @return 分页数据
     */
    @ApiOperation("分页列表查询 报工信息")
    @AutoLog(value = "QueryExport")
    @RequestMapping(method = RequestMethod.GET, value = "/list")
    public Result<?> selectForList(
            EipOperation eipOperation,
            @RequestParam(name = "planStartTimeBegin", defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") Date planStartTimeBegin,
            @RequestParam(name = "planStartTimeFinish", defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") Date planStartTimeFinish,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        if ("undefined".equals(eipOperation.getWoNo())) {
            eipOperation.setWoNo(null);
        }
        Page<EipOperation> page = new Page<EipOperation>(pageNo, pageSize);
        IPage<EipOperation> pageList = eipOperationService.selectForList(page, eipOperation, planStartTimeBegin, planStartTimeFinish);
        return Result.ok(pageList);
    }

    /**
     * 分页列表查询 报工信息
     *
     * @param eipOperation        报工信息
     * @param planStartTimeBegin  起始时间
     * @param planStartTimeFinish 结束时间
     * @param pageNo              起始页
     * @param pageSize            每页页数
     * @param req                 参数
     * @return 分页数据
     */
    @ApiOperation("分页列表查询 报工信息")
    @AutoLog(value = "DataCheck")
    @RequestMapping(method = RequestMethod.GET, value = "/checkList")
    public Result<?> checkList(
            EipOperation eipOperation,
            @RequestParam(name = "planStartTimeBegin", defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") Date planStartTimeBegin,
            @RequestParam(name = "planStartTimeFinish", defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") Date planStartTimeFinish,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        if ("undefined".equals(eipOperation.getWoNo())) {
            eipOperation.setWoNo(null);
        }
        Page<EipOperation> page = new Page<EipOperation>(pageNo, pageSize);
        IPage<EipOperation> pageList = eipOperationService.selectForList(page, eipOperation, planStartTimeBegin, planStartTimeFinish);
        return Result.ok(pageList);
    }

    /**
     * 通过excel导入数据 报工信息
     *
     * @param request  参数
     * @param response 响应
     * @return 是否成功
     */
    @ApiOperation("通过excel导入数据 报工信息")
    @AutoLog(value = "通过excel导入数据 报工信息")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            String fileName = file.getOriginalFilename();
            String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!PoiReadUtil.checkExtension(extension)) {
                return Result.error("文件导入失败:文件格式错误");
            }
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {

                List<EipOperation> list = ExcelImportUtil.importExcel(file.getInputStream(), EipOperation.class, params);
                for (EipOperation eipOperation : list) {
                    eipOperation.setIoflag(eipOperation.getIoflag() == null ? "1" : eipOperation.getIoflag());
//                    EipOperation eipWorkOrderByWoNo = eipOperationService.selectByWoNo(eipOperation.getWoNo());
//                    if (eipWorkOrderByWoNo == null) {
                    eipOperationService.save(eipOperation);
//                    } else {
//                        LambdaQueryWrapper<EipWorkOrder> queryWrapper = new LambdaQueryWrapper<>();
//                        queryWrapper.eq(EipWorkOrder::getWoNo, eipWorkOrder.getWoNo());
//                        eipWorkOrderService.update(eipWorkOrder, queryWrapper);
//                    }
                }
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
//                return Result.error("文件导入失败:" + e.getMessage());
                return Result.error("文件导入失败:请检查excel模板是否正确");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 导出excel 报工信息
     *
     * @param request      参数
     * @param eipOperation 报工信息
     */
    @ApiOperation("导出excel 报工信息")
    @AutoLog(value = "QueryExport")
    @RequestMapping(method = RequestMethod.GET, value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EipOperation eipOperation) {
        return super.exportXls(request, eipOperation, EipOperation.class, "eip_operation");
    }
}